<template>
  <div class="product-edit-container">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑商品' : '添加商品' }}</h2>
    </div>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="product-form"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      
      <el-form-item label="商品分类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="选择分类">
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="商品价格" prop="price">
        <el-input-number v-model="form.price" :precision="2" :min="0" />
      </el-form-item>
      
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="form.description" type="textarea" :rows="3" />
      </el-form-item>
      
      <el-form-item label="商品图片" prop="imageUrl">
        <el-input v-model="form.imageUrl" placeholder="图片URL" />
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const categories = ref([])
const isEdit = ref(false)

// 表单数据
const form = reactive({
  id: null,
  name: '',
  description: '',
  price: 0,
  categoryId: null,
  imageUrl: '',
  status: true
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ]
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await api.get('/categories')
    if (response.data && response.data.status === 'success') {
      categories.value = response.data.data
    } else {
      ElMessage.error('获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 如果是编辑模式，获取商品详情
const fetchProductDetail = async (id) => {
  try {
    const response = await api.get(`/products/${id}`)
    if (response.data && response.data.status === 'success') {
      const product = response.data.data
      
      // 更新表单数据
      form.id = product.id
      form.name = product.name
      form.description = product.description || ''
      form.price = product.price
      form.categoryId = product.categoryId
      form.imageUrl = product.imageUrl || ''
      form.status = product.status
    } else {
      ElMessage.error('获取商品详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
    goBack()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        const data = { ...form }
        
        if (isEdit.value) {
          response = await api.put(`/products/${data.id}`, data)
        } else {
          delete data.id
          response = await api.post('/products', data)
        }
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success(isEdit.value ? '商品更新成功' : '商品添加成功')
          goBack()
        } else {
          ElMessage.error(response.data?.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push('/admin/products')
}

// 组件加载时
onMounted(async () => {
  // 获取分类列表
  await fetchCategories()
  
  // 判断是否为编辑模式
  const id = route.params.id
  if (id) {
    isEdit.value = true
    await fetchProductDetail(id)
  }
})
</script>

<style scoped>
.product-edit-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.product-form {
  max-width: 600px;
}
</style> 